<template>
  <view class="container">
    <!-- 搜索框 -->
    <view class="search-section">
      <view class="search-box">
        <t-icon name="search" size="20px" color="#999" />
        <input 
          class="search-input" 
          placeholder="搜索对话..." 
          v-model="searchKeyword"
          @confirm="handleSearch"
        />
      </view>
    </view>

    <!-- 对话列表 -->
    <view class="dialogues-section">
      <u-swipe-action>
        <u-swipe-action-item 
          v-for="(dialogue, index) in filteredDialogues" 
          :key="dialogue.conversationId"
          :index="index"
          :options="swipeOptions"
          :threshold="80"
          @click="handleSwipeClick($event, dialogue)"
        >
          <view @click="viewDialogueDetail(dialogue)" class="dialogue-item-wrapper">
            <view class="dialogue-item">
              <!-- 头像 -->
              <view class="avatar">
                <view class="avatar-text">{{ getFirstChar(dialogue.title) }}</view>
              </view>
              
              <!-- 对话内容 -->
              <view class="dialogue-content">
                <view class="dialogue-title">{{ dialogue.title }}</view>
                <view class="dialogue-preview">{{ dialogue.preview }}</view>
              </view>
              
              <!-- 时间 -->
              <view class="dialogue-time">{{ dialogue.createTime }}</view>
            </view>
          </view>
        </u-swipe-action-item>
      </u-swipe-action>
    </view>
    
    <!-- 新建对话按钮 -->
    <view class="new-dialogue-btn" @click="startNewDialogue">
      <img :src="'https://youke1.picui.cn/s1/2025/09/18/68cbfee886d99.png'" mode=""></img>
    </view>
  </view>
</template>

<script>
import config from "@/common/config";
export default {
  data() {
    return {
      searchKeyword: '',
      dialogues: [],
      swipeOptions: [
        {
          text: '删除',
          style: {
            backgroundColor: '#ff3b30'
          }
        }
      ]
    };
  },
  
  computed: {
    filteredDialogues() {
      if (!this.searchKeyword) {
        return this.dialogues;
      }
      return this.dialogues.filter(dialogue => 
        dialogue.title.includes(this.searchKeyword) || 
        dialogue.preview.includes(this.searchKeyword)
      );
    }
  },
  
  onLoad() {
    // 页面加载时获取对话列表
    this.getConversationList();
  },
  
  onShow() {
    // 页面显示时也获取对话列表，确保数据是最新的
    this.getConversationList();
  },
  
  methods: {
    // 获取对话列表
    getConversationList() {
      this.$request('/interview/conversation/list', 'GET')
        .then(res => {
          if (res.code === 200) {
            // 处理返回的数据，添加preview字段
            this.dialogues = res.rows.map(item => {
              // 从content中提取预览文本
              let preview = '';
              try {
                const content = JSON.parse(item.content);
                if (Array.isArray(content) && content.length > 0) {
                  // 取第一条消息作为预览
                  preview = content[0].content || '';
                }
              } catch (e) {
                // 如果解析失败，直接使用content
                preview = item.content;
              }
              
              return {
                ...item,
                preview: preview,
                // 格式化时间显示
                createTime: this.formatTime(item.createTime)
              };
            });
          } else {
            console.error('获取对话列表失败:', res.msg);
            uni.showToast({
              title: '获取对话列表失败',
              icon: 'none'
            });
          }
        })
        .catch(err => {
          console.error('获取对话列表失败:', err);
          uni.showToast({
            title: '网络错误',
            icon: 'none'
          });
        });
    },
    
    // 格式化时间显示
    formatTime(time) {
      if (!time) return '';
      // 如果是完整的时间字符串，只取日期部分
      if (time.includes(' ')) {
        return time.split(' ')[0];
      }
      return time;
    },

    // 获取字符串的第一个字符，用于头像显示
    getFirstChar(str) {
      if (!str) return '?';
      return str.charAt(0).toUpperCase();
    },
    
    handleSearch() {
      // 搜索功能
    },
    
    viewDialogueDetail(dialogue) {
      // 跳转到对话详情页
      console.log('跳转到对话详情页:', dialogue);
      uni.navigateTo({
        url: `/pages/askai/detail?conversationId=${dialogue.conversationId}`
      });
    },
    
    startNewDialogue() {
      // 开始新的对话
      uni.navigateTo({
        url: '/pages/askai/detail'
      });
    },

    // 处理滑动操作点击事件
    handleSwipeClick(e, dialogue) {
      console.log('删除按钮点击:', dialogue);
      const { index } = e;
      if (index === 0) { // 删除按钮
        this.deleteConversation(dialogue);
      }
    },
    
    // 删除对话
    deleteConversation(dialogue) {
      // uni.showModal({
      //   title: '确认删除',
      //   content: `确定要删除对话"${dialogue.title}"吗？`,
      //   success: (res) => {
      //     if (res.confirm) {
      //       // 调用删除接口
      //
      //     }
      //   }
      // });
      this.$request(`/interview/conversation/${dialogue.conversationId}`, 'DELETE')
          .then(response => {
            if (response.code === 200) {
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              });
              // 重新获取对话列表
              this.getConversationList();
            } else {
              uni.showToast({
                title: '删除失败',
                icon: 'none'
              });
            }
          })
          .catch(err => {
            console.error('删除对话失败:', err);
            uni.showToast({
              title: '删除失败',
              icon: 'none'
            });
          });
    }
  }
};
</script>

<style scoped lang="scss">
.container {
  padding: 0;
  padding-bottom: 80px;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.search-section {
  padding: 10px 15px;
  background-color: #f5f5f5;
}

.search-box {
  display: flex;
  align-items: center;
  background-color: #ebebeb;
  padding: 8px 15px;
  border-radius: 4px;
}

.search-input {
  flex: 1;
  margin-left: 10px;
  font-size: 14px;
  border: none;
  outline: none;
  background: transparent;
}

.dialogues-section {
  background-color: #fff;
}

.dialogue-item-wrapper {
  border-bottom: 1px solid #ebebeb;
}

.dialogue-item-wrapper:last-child {
  border-bottom: none;
}

.dialogue-item {
  display: flex;
  padding: 12px 15px;
  align-items: center;
}

.avatar {
  width: 48px;
  height: 48px;
  border-radius: 6px;
  background: linear-gradient(135deg, #008cff, #00cc86);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  flex-shrink: 0;
}

.avatar-text {
  color: #fff;
  font-size: 18px;
  font-weight: 500;
}

.dialogue-content {
  flex: 1;
  overflow: hidden;
}

.dialogue-title {
  font-size: 17px;
  color: #333;
  margin-bottom: 3px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.dialogue-preview {
  font-size: 14px;
  color: #999;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.dialogue-time {
  font-size: 12px;
  color: #999;
  margin-left: 5px;
  flex-shrink: 0;
}

.new-dialogue-btn {
  position: fixed;
  bottom: 60px;
  right: 30px;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 15px rgba(0, 122, 255, 0.3);
  z-index: 999;
  img{
    width: 50px;
    height: 50px;
  }
}
</style>